const App = getApp()
var WxCode = '';
var WxEncryptedData = '';
var WxIv = '';
var sid = 0;
var surl = '';
var longitude = "";
var latitude = "";
var on_index = 0; //当前选中
var util = require('../utils/util.js');
var QQMapWX = require('../utils/qqmap-wx-jssdk.js');
Page({
  data: {
    bl1: false, //免责声明
    bl3: false, //用户授权
    bl4: true, //启事删除
    bl6: true, //寻主删除
    dogdata: [],
    longitude: '',
    latitude: '',
    xcxinfo: {}, //小程序基础信息
    userInfo: {
      uid: 0,
      nickName: '点击登录',
      avatarUrl: '/img/icon_1.png',
    },
    painting: {},
    shareImage: '',
    cityName: '',
    drawIng: false,
    timeover: null,
    shareImageList: []
  },
  shareReady(imgA, imgB) {
    let painting = {
      width: 500,
      height: 400,
      clear: true,
      views: [{
        type: 'image',
        url: imgA,
        top: 0,
        left: 0,
        width: 500,
        height: 400
      }, {
        type: 'image',
        url: imgB,
        top: 0,
        left: 0,
        width: 416,
        height: 53
      }]
    }
    this.setData({
      painting
    })
  },
  eventGetImage(event) {
    wx.hideLoading()
    const {
      tempFilePath,
      errMsg
    } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      console.log('绘图完成')
      this.setData({
        shareImage: tempFilePath,
        drawIng: false,
      })
    }
  },
  onShareAppMessage: function (e) {
    let slet = this;
    if (e.from == 'button') //按钮分享
    {
      let dogdata = slet.data.dogdata;
      let index = e.target.dataset.index;
      let type = dogdata[index].type;
      let dogid = dogdata[index].id;
      let doginfo = dogdata[index]

      // 如果有图片
      if (this.data.shareImageList[index]) {
        if (type == 0) {
          return {
            title: `【${this.data.cityName.replace('市', '')}寻狗】走丢了一只${doginfo.pz.replace('犬', '')}，希望各位宠友留意一下`,
            imageUrl: this.data.shareImageList[index],
            path: '/pages/fj/doginfo?id=' + dogid
          }
        } else {
          return {
            title: `【${this.data.cityName.replace('市', '')}寻主】捡到了一只${doginfo.pz.replace('犬', '')}，希望狗狗主人联系我`,
            imageUrl: this.data.shareImageList[index],
            path: '/pages/fj/masterinfo?id=' + dogid
          }
        }
      }
      // 没有图片
      this.setData({
        drawIng: true,
      })
      wx.showLoading({
        title: '分享图片绘制中...',
        mask: true,
      })
      if (this.data.timeover) {
        clearInterval(this.data.timeover)
        this.setData({
          timeover: null,
        })
      }
      this.shareReady(doginfo.img, type == 0 ? '/img/share-tit-ico1.png' : '/img/share-tit-ico2.png')
      this.reverseMap(doginfo)
      return new Promise((resolve) => {
        this.data.timeover = setInterval(() => {
          if (this.data.drawIng === false) {
            wx.hideLoading()
            clearInterval(this.data.timeover)
            let list = [...this.data.shareImageList]
            list.push(this.data.shareImage)
            this.setData({
              timeover: null,
              drawIng: true,
              shareImageList: list
            })
            if (type == 0) {
              resolve({
                title: `【${this.data.cityName.replace('市', '')}寻狗】走丢了一只${doginfo.pz.replace('犬', '')}，希望各位宠友留意一下`,
                imageUrl: this.data.shareImage,
                path: '/pages/fj/doginfo?id=' + dogid
              })
            } else {
              resolve({
                title: `【${this.data.cityName.replace('市', '')}寻主】捡到了一只${doginfo.pz.replace('犬', '')}，希望狗狗主人联系我`,
                imageUrl: this.data.shareImage,
                path: '/pages/fj/masterinfo?id=' + dogid
              })
            }
          }
        }, 500)
      })
    } else {
      return {
        title: `【全国公益寻宠平台】互助寻宠 互助提供寻宠线索 互助分享传播`,
        imageUrl: '/img/share-defa.png',
        path: '/pages/index'
      }
    }
  },
  reverseMap(doginfo) {
    let qqmapsdk = new QQMapWX({
      key: getApp().globalData.mapkey
    });
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: doginfo.latitude,
        longitude: doginfo.longitude
      },
      success: ({
        result
      }) => {
        this.setData({
          cityName: result && result.address_component && result.address_component.city
        })
      },
    });
  },
  onShareTimeline: function (res) { //分享到朋友圈
    return {
      title: `【全国公益寻宠平台】互助寻宠 互助提供寻宠线索 互助分享传播`,
      imageUrl: '/img/share-defa.png',
    }
  },
  onLoad: function (options) {
    //wx.setStorageSync('LoginSessionKey', '2561ED39BE3EA0EAF73878434756A9B7');
    let slet = this;
    let systemInfo = wx.getSystemInfoSync();
    let statusBarHeight = systemInfo.statusBarHeight;
    statusBarHeight = statusBarHeight * 2;
    let sysButton = wx.getMenuButtonBoundingClientRect();
    getApp().globalData.statusBarHeight = sysButton.top * 2;

    wx.request({
      url: getApp().data.apiUrl + '/GetInformation.ashx',
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log('xcxinfo:', resdata);
        getApp().globalData.xcxinfodata = resdata;
        getApp().data.sitename = resdata.name;
        wx.setNavigationBarTitle({ //设置标题
          title: resdata.name
        });
        slet.setData({
          xcxinfo: resdata
        })
      }
    })
    on_index = 0;
  },
  onShow(e) {
    let slet = this;
    if (getApp().globalData.longitude == "" || getApp().globalData.latitude == "") {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          console.log(res);
          latitude = res.latitude;
          longitude = res.longitude;
          getApp().globalData.longitude = longitude;
          getApp().globalData.latitude = latitude;
          slet.getUserInfo(); //获取用户信息
        },
        fail: function (res2) {
          console.log(res2);
          wx.showModal({
            title: '请打开手机定位，确认授权',
            content: '确保手机定位已开启，允许获取位置信息',
            confirmText: '重新授权',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({ //切换到授权设置界面
                  success: function (dataAu) {
                    console.log('123:', dataAu.authSetting);
                    if (dataAu.authSetting['scope.userLocation']) {
                      latitude = dataAu.latitude;
                      longitude = dataAu.longitude;
                      getApp().globalData.longitude = longitude;
                      getApp().globalData.latitude = latitude;
                      slet.getUserInfo(); //获取用户信息
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      slet.getUserInfo(); //获取用户信息
    }
  },
  openMap(e) //打开地图
  {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'qs/map?id=' + id,
    })
  },
  getUserInfo() //获取用户信息
  {
    let slet = this;
    if (wx.getStorageSync('LoginSessionKey') != '') //读取缓存
    {
      wx.showLoading({
        title: '加载中',
        mask: true,
      })
      getApp().data.SessionKey = wx.getStorageSync('LoginSessionKey');
      if (getApp().data.SessionKey == "") {
        getApp().data.SessionKey = wx.getStorageSync('LoginSessionKey');
      }
      wx.request({
        url: getApp().data.apiUrl + '/SelUser.ashx',
        data: {
          token: getApp().data.SessionKey,
          latitude: latitude,
          longitude: longitude,
        },
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
          console.log('userInfo:', resdata);
          if (resdata.status == 1) //未审核
          {
            wx.showToast({
              title: '账号未审核',
              icon: 'success',
              duration: 1000
            })
          } else if (resdata.status == 2) //已注册
          {
            slet.getDogList(resdata.uid);
            slet.setData({
              bl3: true,
              userInfo: resdata
            })
          }
        }
      })
    } else {
      slet.setData({
        dogdata: []
      })
    }
  },
  ImgTap: function (e) { // 图片点击事件
    let slet = this;
    let index = e.currentTarget.dataset.index;
    let dogdata = slet.data.dogdata;
    let doginfo = dogdata[index];
    var nowImgUrl = e.target.dataset.src;
    console.log(nowImgUrl);
    let imageUrls = [];
    if (doginfo.img != '' && doginfo.imgtype == 0) {
      imageUrls.push(doginfo.img);
    }
    if (doginfo.img1 != '' && doginfo.imgtype1 == 0) {
      imageUrls.push(doginfo.img1);
    }
    if (doginfo.img2 != '' && doginfo.imgtype2 == 0) {
      imageUrls.push(doginfo.img2);
    }
    wx.previewImage({
      current: nowImgUrl,
      urls: imageUrls
    })
  },
  onSubscribe1(e) {
    let slet = this;
    let index = e.currentTarget.dataset.index;
    let dogdata = slet.data.dogdata;
    let type = dogdata[index].type;
    let dogid = dogdata[index].id;
    let xcxinfo = slet.data.xcxinfo;
    let tmplIds1 = xcxinfo.tmplIds1;
    if (tmplIds1.length < 10) {
      wx.navigateTo({
        url: 'fj/doginfo?id=' + dogid
      })
      return;
    }
    let tmplIds = '[' + tmplIds1 + ']' //订阅消息ID
    tmplIds = tmplIds.replace(/@/g, '"');
    tmplIds = JSON.parse(tmplIds);
    console.log(tmplIds);
    // 调用微信 API 申请发送订阅消息
    wx.requestSubscribeMessage({
      // 传入订阅消息的模板id，模板 id 可在小程序管理后台申请
      tmplIds: tmplIds,
      success(res) {
        console.log(res);
        //申请订阅成功
        if (res.errMsg === 'requestSubscribeMessage:ok') {}
        wx.navigateTo({
          url: 'fj/doginfo?id=' + dogid
        })
      }
    });
  },
  onSubscribe2(e) {
    let slet = this;
    let index = e.currentTarget.dataset.index;
    let dogdata = slet.data.dogdata;
    let type = dogdata[index].type;
    let dogid = dogdata[index].id;
    let xcxinfo = slet.data.xcxinfo;
    let tmplIds1 = xcxinfo.tmplIds2;
    if (tmplIds1.length < 10) {
      wx.navigateTo({
        url: 'fj/masterinfo?id=' + dogid
      })
      return;
    }
    let tmplIds = '[' + tmplIds1 + ']' //订阅消息ID
    tmplIds = tmplIds.replace(/@/g, '"');
    tmplIds = JSON.parse(tmplIds);
    console.log(tmplIds);
    // 调用微信 API 申请发送订阅消息
    wx.requestSubscribeMessage({
      // 传入订阅消息的模板id，模板 id 可在小程序管理后台申请
      tmplIds: tmplIds,
      success(res) {
        console.log(res);
        //申请订阅成功
        if (res.errMsg === 'requestSubscribeMessage:ok') {}
        wx.navigateTo({
          url: 'fj/masterinfo?id=' + dogid
        })
      }
    });
  },
  getDogList(uid) {
    let slet = this;
    wx.request({
      url: getApp().data.apiUrl + '/GetDogList.ashx',
      data: {
        uid: uid
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log(resdata);
        slet.setData({
          dogdata: resdata.data
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  toApp(e) //小程序跳转
  {
    let slet = this;
    let index_1 = e.currentTarget.dataset.index;
    let xcxinfo = slet.data.xcxinfo;
    let xcxinfoimg = xcxinfo.imgdata[index_1];
    if (xcxinfoimg.style == 1) {
      let appId = xcxinfoimg.url; //appid
      let unionid = '123456';
      wx.navigateToMiniProgram({
        appId: appId,
        path: 'pages/stars/stars?unionid=' + unionid,
        extraData: {
          unionid: unionid
        },
        envVersion: 'release',
        success(res) {
          // 打开成功
        }
      })
    } else {
      let tmplIds2 = getApp().globalData.xcxinfodata.tmplIds6;
      if (tmplIds2.length > 10) {
        let tmplIds = '[' + tmplIds2 + ']' //订阅消息ID
        tmplIds = tmplIds.replace(/@/g, '"');
        tmplIds = JSON.parse(tmplIds);
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            wx.navigateTo({
              url: '/dsf/dsf/dsf?url=' + xcxinfoimg.url,
            })
            return;
          }
        })
      } else {
        wx.navigateTo({
          url: '/dsf/dsf/dsf?url=' + xcxinfoimg.url,
        })
      }
    }
  },
  bindFz(e) //一键复制
  {
    let slet = this;
    let xcxinfo = slet.data.xcxinfo;
    var text = xcxinfo.wx;
    wx.setClipboardData({
      data: text,
      success() {}
    })
  },
  bindLogin() //登录
  {
    let slet = this;
    let bl3 = slet.data.bl3;
    let userInfo = slet.data.userInfo;
    if (userInfo.uid == 0) {
      slet.setData({
        bl3: false
      })
      return;
    }
  },
  toFb(e) //发布
  {
    let slet = this;
    let bl3 = slet.data.bl3;
    let userInfo = slet.data.userInfo;
    if (userInfo.uid == 0) {
      slet.setData({
        bl3: false
      })
      return;
    }
    console.log('longitude-index:', getApp().globalData.longitude);
    if (getApp().globalData.longitude != "" && getApp().globalData.latitude != "") {
      wx.redirectTo({
        url: 'qs/index'
      })
    } else {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          console.log(res);
          latitude = res.latitude;
          longitude = res.longitude;
          getApp().globalData.longitude = longitude;
          getApp().globalData.latitude = latitude;
          wx.redirectTo({
            url: 'qs/index'
          })
        },
        fail: function (res2) {
          console.log(res2);
          wx.showModal({
            title: '请打开手机定位，确认授权',
            content: '确保手机定位已开启，允许获取位置信息',
            confirmText: '重新授权',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({ //切换到授权设置界面
                  success: function (dataAu) {
                    console.log('123:', dataAu.authSetting);
                    if (dataAu.authSetting['scope.userLocation']) {
                      latitude = dataAu.latitude;
                      longitude = dataAu.longitude;
                      getApp().globalData.longitude = longitude;
                      getApp().globalData.latitude = latitude;
                      wx.redirectTo({
                        url: 'qs/index'
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    }
  },
  toFj(e) //附近
  {
    let slet = this;
    let bl3 = slet.data.bl3;
    let userInfo = slet.data.userInfo;
    if (userInfo.uid == 0) {
      slet.setData({
        bl3: false
      })
      return;
    }
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        latitude = res.latitude;
        longitude = res.longitude;
        getApp().globalData.longitude = longitude;
        getApp().globalData.latitude = latitude;
        let tmplIds2 = getApp().globalData.xcxinfodata.tmplIds4;
        console.log(tmplIds2);
        if (tmplIds2.length > 10) {
          let tmplIds = '[' + tmplIds2 + ']' //订阅消息ID
          tmplIds = tmplIds.replace(/@/g, '"');
          tmplIds = JSON.parse(tmplIds);
          wx.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
              wx.navigateTo({
                url: 'fj/index'
              })
              return;
            }
          })
        } else {
          wx.navigateTo({
            url: 'fj/index'
          })
          return;
        }
      },
      fail: function (res2) {
        console.log(res2);
        wx.showModal({
          title: '请打开手机定位，确认授权',
          content: '确保手机定位已开启，允许获取位置信息',
          confirmText: '重新授权',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({ //切换到授权设置界面
                success: function (dataAu) {
                  console.log('123:', dataAu.authSetting);
                  if (dataAu.authSetting['scope.userLocation']) {
                    latitude = dataAu.latitude;
                    longitude = dataAu.longitude;
                    getApp().globalData.longitude = longitude;
                    getApp().globalData.latitude = latitude;
                    let tmplIds2 = getApp().globalData.xcxinfodata.tmplIds4;
                    if (tmplIds2.length > 10) {
                      let tmplIds = '[' + tmplIds2 + ']' //订阅消息ID
                      tmplIds = tmplIds.replace(/@/g, '"');
                      tmplIds = JSON.parse(tmplIds);
                      wx.requestSubscribeMessage({
                        tmplIds: tmplIds,
                        success(res) {
                          wx.navigateTo({
                            url: 'fj/index'
                          })
                          return;
                        }
                      })
                    } else {
                      wx.navigateTo({
                        url: 'fj/index'
                      })
                      return;
                    }
                  }
                }
              })
            }
          }
        })
      }
    })
    console.log(longitude);
    if (longitude != "") {
      getApp().globalData.longitude = longitude;
      getApp().globalData.latitude = latitude;
      let tmplIds2 = getApp().globalData.xcxinfodata.tmplIds4;
      if (tmplIds2.length > 10) {
        let tmplIds = '[' + tmplIds2 + ']' //订阅消息ID
        tmplIds = tmplIds.replace(/@/g, '"');
        tmplIds = JSON.parse(tmplIds);
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            wx.navigateTo({
              url: 'fj/index'
            })
          }
        })
      } else {
        wx.navigateTo({
          url: 'fj/index'
        })
      }
    }
  },
  onGotUserInfo: function (e) { //授权回调
    if (e.detail.rawData != undefined) {
      wx.showLoading({
        title: '加载中',
        mask: true,
      })
      let slet = this;
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      wx.login({ //login流程
        success: function (res) { //登录成功
          if (res.code) {
            WxCode = res.code;
            WxEncryptedData = encodeURIComponent(encryptedData);
            WxIv = iv;
            wx.request({
              url: getApp().data.apiUrl + '/Login.ashx',
              data: {
                code: WxCode,
                encryptedData: WxEncryptedData,
                iv: WxIv,
                uid: sid
              },
              method: 'GET',
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
                console.log(resdata);
                if (resdata.status == 1) //注册成功/未审核
                {
                  wx.showToast({
                    title: '账号未审核',
                    icon: 'success',
                    duration: 1000
                  })
                } else if (resdata.status == 2) //已注册
                {
                  wx.setStorageSync('LoginSessionKey', resdata.signature);
                  getApp().data.SessionKey = resdata.signature;
                  slet.getDogList(resdata.uid);
                  slet.setData({
                    bl3: true,
                    userInfo: resdata
                  })
                }
              }

            })
          }
        },
        fail: function () { //失败
        },
        complete: function () { //完成
        }
      })
    } else {
      wx.showToast({
        title: '不授权无法使用',
        icon: 'success',
        duration: 1000
      })
    }
  },
  toWd(e) {
    wx.navigateTo({
      url: 'xq/card',
    })
  },
  toXq(e) {
    wx.navigateTo({
      url: 'xq/release',
    })
    // wx.navigateTo({
    //   url: 'time',
    // })
  },
  toXq1(e) {
    wx.showToast({
      title: '只能发布一次',
      icon: 'success',
      duration: 1000
    })
  },
  toXq(e) {
    wx.navigateTo({
      url: 'xq/nearby',
    })
  },
  toClose(e) { //关闭
    let slet = this;
    slet.setData({
      bl1: false,
    })
  },
  toOpen(e) { //打开
    let slet = this;
    slet.setData({
      bl1: true,
    })
  },
  openDel1(e) //打开删除窗口
  {
    let slet = this;
    on_index = e.currentTarget.dataset.index;
    slet.setData({
      bl4: false,
    })
  },
  closeDel1() //关闭删除窗口
  {
    let slet = this;
    slet.setData({
      bl4: true,
    })
  },
  bindSubmit1(e) //已找到爱宠
  {
    let slet = this;
    let dogdata = slet.data.dogdata;
    wx.request({
      url: getApp().data.apiUrl + '/UpdateDogInfo.ashx',
      data: {
        token: wx.getStorageSync('LoginSessionKey'),
        dogid: dogdata[on_index].id,
        state: 2, //已找到
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log(resdata);
        if (resdata.state == 1) {
          dogdata[on_index].state = 2;
          wx.showModal({
            title: '提示',
            content: '操作成功',
            showCancel: false,
            success: function (res) {
              slet.setData({
                dogdata: dogdata,
                bl4: true
              })
            }
          })
        } else {
          wx.showToast({
            title: resdata.msg,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  openDel2(e) //打开删除窗口
  {
    let slet = this;
    on_index = e.currentTarget.dataset.index;
    slet.setData({
      bl6: false,
    })
  },
  closeDel2() //关闭删除窗口
  {
    let slet = this;
    slet.setData({
      bl6: true,
    })
  },
  bindSubmit2(e) //已经找到主人
  {
    let slet = this;
    let dogdata = slet.data.dogdata;
    wx.request({
      url: getApp().data.apiUrl + '/UpdateDogInfo.ashx',
      data: {
        token: wx.getStorageSync('LoginSessionKey'),
        dogid: dogdata[on_index].id,
        state: 2, //已找到
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log(resdata);
        if (resdata.state == 1) {
          dogdata[on_index].state = 2;
          wx.showModal({
            title: '提示',
            content: '操作成功',
            showCancel: false,
            success: function (res) {
              slet.setData({
                dogdata: dogdata,
                bl6: true
              })
            }
          })
        } else {
          wx.showToast({
            title: resdata.msg,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  delSubmit2(e) //寻主启事删除
  {
    let slet = this;
    let dogdata = slet.data.dogdata;
    wx.request({
      url: getApp().data.apiUrl + '/UpdateDogInfo.ashx',
      data: {
        token: wx.getStorageSync('LoginSessionKey'),
        dogid: dogdata[on_index].id,
        state: 0, //删除
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log(resdata);
        if (resdata.state == 1) {
          dogdata.splice(on_index, 1);
          wx.showModal({
            title: '提示',
            content: '删除成功',
            showCancel: false,
            success: function (res) {
              slet.setData({
                dogdata: dogdata,
                bl6: true
              })
            }
          })
        } else {
          wx.showToast({
            title: resdata.msg,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  }
})